package com.sky.prototype;

import java.io.*;

/**
 * date : 2024-09-18
 *
 * @author : wushikai
 */


class User implements Serializable, Cloneable {

    private String name;

    User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public Object deepClone1() throws IOException, ClassNotFoundException, OptionalDataException {
        //将对象写入流中
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bao);
        oos.writeObject(this);

        //将对象从流中取出
        ByteArrayInputStream bis = new ByteArrayInputStream(bao.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        return (ois.readObject());
    }

    public Object deepClone2() throws IOException, ClassNotFoundException, OptionalDataException, CloneNotSupportedException {
        User user = (User) super.clone();
        String name = new String(user.name);
        user.setName(name);
        return user;

    }


}


public class PrototypeApplication {

    private static Integer MAX_NUM = 1000 * 1000 * 1000;

    public static void main(String[] args) throws Exception {

        System.out.println("System.currentTimeMillis() = " + System.currentTimeMillis());
        for (int i = 0; i < MAX_NUM; i++) {
            new User("obj" + i);
//            if (i%(10*1000*1000)==0){
//                System.out.println("创建数量==>"+ i );
//            }
        }
        System.out.println("System.currentTimeMillis() = " + System.currentTimeMillis());

        User prototype = new User("obj_prototype");
        System.out.println(prototype.getName().hashCode());
        System.out.println("System.currentTimeMillis() = " + System.currentTimeMillis());
        for (int i = 0; i < MAX_NUM; i++) {
//            User user_clone = (User) user.deepClone();
            User user = (User) prototype.deepClone1();
            if (i == 0) {
                System.out.println(user.getName().hashCode());
            }
//            user_clone.setName(  "obj" + i);
//            if (i%(10*1000*1000)==0){
//                System.out.println("创建数量==>"+ i );
//            }
        }
        System.out.println("System.currentTimeMillis() = " + System.currentTimeMillis());


    }
}
